package com.haircut.sys.service.login;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.RegisteredPayload;
import com.haircut.sys.constant.CacheConstants;
import com.haircut.sys.vo.user.LoginUserVo;
import com.modular.security.JwtTokenService;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class TokenService
{
    private static final Logger logger =  LoggerFactory.getLogger(TokenService.class);

    // 令牌自定义标识
//    @Value("${token.header}")
    private String header;

    // 令牌秘钥
//    @Value("${token.secret}")
    private String secret ="sdfsdfsdfsdfdsf";

    // 令牌有效期（默认30分钟）
//    @Value("${token.expireTime}")
    private int expireTime =30;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private JwtTokenService jwtTokenService;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUserVo getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StrUtil.isNotEmpty(token))
        {
//            try
//            {
//                Claims claims = parseToken(token);
//                // 解析对应的权限以及用户信息
//                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
//                String userKey = getTokenKey(uuid);
//                LoginUser user = redisCache.getCacheObject(userKey);
//                return user;
//            }
//            catch (Exception e)
//            {
//                log.error("获取用户信息异常'{}'", e.getMessage());
//            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUserVo loginUser)
    {
        if (ObjectUtil.isNotNull(loginUser) && StrUtil.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
//        if (StringUtils.isNotEmpty(token))
//        {
//            String userKey = getTokenKey(token);
//            redisCache.deleteObject(userKey);
//        }
    }


    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUserVo loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUserVo loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getUserId());
        redisTemplate.opsForValue().set(userKey, JSONUtil.toJsonStr(loginUser), expireTime, TimeUnit.MINUTES);
    }


    /**
     * 从数据声明生成令牌
     *
     * @return 令牌
     */
    public void saveToken(LoginUserVo loginUserVo)
    {
       jwtTokenService.createToken(loginUserVo);
    }


    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(header);
        if (StrUtil.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX))
        {
            token = token.replace(CacheConstants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid)
    {
        return StrUtil.format(CacheConstants.MANAGER_LOGIN_TOKEN_KEY,uuid);
    }
}
